package org.framework2.test.webserver.http.servlet;

import java.util.HashMap;
import java.util.Map;

import javax.script.Compilable;
import javax.script.CompiledScript;
import javax.script.ScriptEngineManager;

import org.framework2.test.webserver.http.WSTMHttpServlet;
import org.framework2.test.webserver.http.request.AbstractWSTMHttpRequest;
import org.framework2.test.webserver.http.response.AbstractWSTMHttpResponse;
import org.framework2.test.webserver.http.script.ScriptFileAdapter;

/**
 * <p>
 * 脚本文件适配Servlet处理器
 * </p>
 * @see 
 * @author ahli
 * @version WebServerTestMockV1, 2010-8-19
 * @since WebServerTestMockV1
 */
public class AdapterScriptFileServlet implements WSTMHttpServlet {

	private ScriptFileAdapter scriptFileAdapter;
	
	//private final ScriptEngine jsEngine = new ScriptEngineManager().getEngineByName("js");
	private final ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
//	private final Compilable compilable = (Compilable)scriptEngineManager.getEngineByName("js");

	
	private Map<String, Object> beanMap = new HashMap<String, Object>();
	
	public void setScriptFileAdapter(ScriptFileAdapter scriptFileAdapter) {
		this.scriptFileAdapter = scriptFileAdapter;
	}
	
	public Map<String, Object> getBeanMap() {
		return beanMap;
	}

	public void setBeanMap(Map<String, Object> beanMap) {
		this.beanMap = beanMap;
	}

	@Override
	public void execute(AbstractWSTMHttpRequest request,
			AbstractWSTMHttpResponse response) throws Exception {
//		jsEngine.put("request", request);
//		jsEngine.put("response", response);
//		for(Map.Entry<String, Object> entry : this.beanMap.entrySet()){
//			jsEngine.put(entry.getKey(), entry.getValue());
//		}
//		jsEngine.eval(scriptFileAdapter.getScriptContent(request.getRequestURI()));
		Compilable compilable = (Compilable)scriptEngineManager.getEngineByName("js");
		CompiledScript compiledScript = compilable.compile(scriptFileAdapter.getScriptContent(request.getRequestURI()));
		compiledScript.getEngine().put("request", request);
		compiledScript.getEngine().put("response", response);
		for(Map.Entry<String, Object> entry : this.beanMap.entrySet()){
			compiledScript.getEngine().put(entry.getKey(), entry.getValue());
		}
		compiledScript.eval();
	}
}
